package top.ruanlitao.shortlink.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
public class AddOriginalHostHeaderFilter extends AbstractGatewayFilterFactory<Object> {

    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest().mutate()
                    // .header("X-Original-Host", Objects.requireNonNull(exchange.getRequest().getHeaders().getHost()).getHostName())
                    .header("X-Original-Host", Objects.requireNonNull(exchange.getRequest().getRemoteAddress()).getAddress().getHostAddress())
                    .build();
            return chain.filter(exchange.mutate().request(request).build());
        };
    }
}
